const { userModel } = require('../models/userModel.js');
// token插件
const jwt = require('jsonwebtoken');
// 上传图片插件
const { uploadFiles } = require('../utils/handleFiles')


// 验证登录用户------
async function login(req, res, next) {
    const { username, password } = req.body;

    const result = await userModel.find({
        name: username,
        pass: password
    })
    console.log(result);
    if (result.length > 0) {
        // 生成 token
        const token = jwt.sign(
            { user: result[0] }, //  用户信息
            'hello',  // 密钥，任意字符串
            { expiresIn: '24h' } // 设置有效期
        )

        res.send({
            code: 200,
            message: '登录成功~',
            result,
            token: 'Bearer ' + token
        })
    }
}


// 注册用户-----
async function register(req, res, next) {
    const { propertyName, registerName, registerPass } = req.body;
    console.log(propertyName, registerName, registerPass);
    // 验证重复用户名
    const findUser = await userModel.find({
        name: registerName,
    })
    if (findUser.length == 0) {
        const result = await userModel.create({
            name: registerName,
            pass: registerPass,
            propertyName
        })
        if (result) {
            res.send({
                code: 200,
                message: '注册成功'
            })
        }
    } else {
        res.send({
            code: 500,
            message: '用户名重复,请重新输入'
        })
    }
}

// 上传图片------------------
async function upload(req, res, next) {
    const uploadImages = uploadFiles({
        // 图片上传成功后的存储路径
        // path: './public/assets',
        // key: 'file',
        // size: 1000
    });
    uploadImages(req, res, (error) => {
        if (error) {
            console.log('图片上传失败', error);
        } else {
            console.log('图片上传成功');
            // 输出上传成功后的图片信息
            console.log(req.files);
            res.send({
                message: '图片上传成功',
                code: 200,
                path: 'http://localhost:3000/images/' + req.files[0].filename
            })
        }
    });
}

//修改用户资料 
async function updateInfo(req, res, next) {
    console.log(req.params);
    console.log(req.body);
    const result = await userModel.updateOne(
        { _id: req.params },
        {...req.body}
    )
    const data = await userModel.find({ _id:req.params })
    if(result.nModified > 0){
        res.send({
            code:200,
            message:'修改成功',
            data
        })
    }
    console.log(result);
}

module.exports = {
    register,
    login,
    upload,
    updateInfo
}